#include "collattr.h"

CollAttr::CollAttr()
{
this->setAttribute(Qt::WA_DeleteOnClose);
setupUi(this);
readSettings();

collNomTableView->addAction(actionNoms);
collStatesTableView->addAction(actionState);
collEpochsTableView->addAction(actionEpoch);
collMarksTableView->addAction(actionMark);
collMetalsTableView->addAction(actionMetal);
collEdgeIDsTableView->addAction(actionEdgeID);
collMintTableView->addAction(actionMint);
collTypesTableView->addAction(actionType);
collUndertypesTableView->addAction(actionUndertype);
collStatusTableView->addAction(actionStatus);
collUnitsTableView->addAction(actionUnits);
collCurrTableView->addAction(actionCurr);
collCondTableView->addAction(actionCond);
collCertAuthTableView->addAction(actionCA);
collLocTableView->addAction(actionLoc);
collCatalogsTableView->addAction(actionCatalogs);
collObvSymbolsTableView->addAction(actionObvSymb);
collRevSymbolsTableView->addAction(actionRevSymb);
collObvTypesTableView->addAction(actionObvType);
collRevTypesTableView->addAction(actionRevType);
collAuctTableView->addAction(actionAuct);
collRecTypesTableView->addAction(actionRecType);

collNomTableView->addAction(actionNomsD);
collStatesTableView->addAction(actionStateD);
collEpochsTableView->addAction(actionEpochD);
collMarksTableView->addAction(actionMarkD);
collMetalsTableView->addAction(actionMetalD);
collEdgeIDsTableView->addAction(actionEdgeIDD);
collMintTableView->addAction(actionMintD);
collTypesTableView->addAction(actionTypeD);
collUndertypesTableView->addAction(actionUndertypeD);
collStatusTableView->addAction(actionStatusD);
collUnitsTableView->addAction(actionUnitsD);
collCurrTableView->addAction(actionCurrD);
collCondTableView->addAction(actionCondD);
collCertAuthTableView->addAction(actionCAD);
collLocTableView->addAction(actionLocD);
collCatalogsTableView->addAction(actionCatalogsD);
collObvSymbolsTableView->addAction(actionObvSymbD);
collRevSymbolsTableView->addAction(actionRevSymbD);
collObvTypesTableView->addAction(actionObvTypeD);
collRevTypesTableView->addAction(actionRevTypeD);
collAuctTableView->addAction(actionAuctD);
collRecTypesTableView->addAction(actionRecTypeD);

tableviews << collNomTableView
           << collStatesTableView
           << collEpochsTableView
           << collMarksTableView
           << collMetalsTableView
           << collEdgeIDsTableView
           << collMintTableView
           << collTypesTableView
           << collUndertypesTableView
           << collStatusTableView
           << collUnitsTableView
           << collCurrTableView
           << collCondTableView
           << collCertAuthTableView
           << collLocTableView
           << collCatalogsTableView
           << collObvSymbolsTableView
           << collRevSymbolsTableView
           << collObvTypesTableView
           << collRevTypesTableView
           << collAuctTableView
           << collRecTypesTableView;

definition_field_names["denominations"] = QLatin1String("nom");
definition_field_names["states"]        = QLatin1String("state");
definition_field_names["epochs"]        = QLatin1String("epoch");
definition_field_names["notes"]         = QLatin1String("mark");
definition_field_names["materials"]     = QLatin1String("material");
definition_field_names["edgeids"]       = QLatin1String("edgeid");
definition_field_names["mints"]         = QLatin1String("mint");
definition_field_names["types"]         = QLatin1String("obj_type");
definition_field_names["undertypes"]    = QLatin1String("undertype");
definition_field_names["obvsymbs"]      = QLatin1String("obvsymb");
definition_field_names["obvtypes"]      = QLatin1String("obvtype");
definition_field_names["revsymbs"]      = QLatin1String("revsymb");
definition_field_names["revtypes"]      = QLatin1String("revtype");
definition_field_names["auctions"]      = QLatin1String("auction");
definition_field_names["catalogs"]      = QLatin1String("catalog_name");

definition_tables["denominations"]      = QLatin1String("noms_reg");
definition_tables["states"]             = QLatin1String("states_reg");
definition_tables["epochs"]             = QLatin1String("epochs_reg");
definition_tables["notes"]              = QLatin1String("marks_reg");
definition_tables["materials"]          = QLatin1String("materials_reg");
definition_tables["edgeids"]            = QLatin1String("edgeids_reg");
definition_tables["mints"]              = QLatin1String("mints_reg");
definition_tables["types"]              = QLatin1String("types_reg");
definition_tables["undertypes"]         = QLatin1String("undertypes_reg");
definition_tables["obvsymbs"]           = QLatin1String("obvsymbs_reg");
definition_tables["obvtypes"]           = QLatin1String("obvtypes_reg");
definition_tables["revsymbs"]           = QLatin1String("revsymbs_reg");
definition_tables["revtypes"]           = QLatin1String("revtypes_reg");
definition_tables["auctions"]           = QLatin1String("auctions_reg");
definition_tables["catalogs"]           = QLatin1String("catalogs_reg");

definition_id_names["denominations"]      = QLatin1String("nom_id");
definition_id_names["states"]             = QLatin1String("state_id");
definition_id_names["epochs"]             = QLatin1String("epoch_id");
definition_id_names["notes"]              = QLatin1String("marks_id");
definition_id_names["materials"]          = QLatin1String("material_id");
definition_id_names["edgeids"]            = QLatin1String("edgeid_id");
definition_id_names["mints"]              = QLatin1String("mint_id");
definition_id_names["types"]              = QLatin1String("type_id");
definition_id_names["undertypes"]         = QLatin1String("undertype_id");
definition_id_names["obvsymbs"]           = QLatin1String("obvsymb_id");
definition_id_names["obvtypes"]           = QLatin1String("obvtype_id");
definition_id_names["revsymbs"]           = QLatin1String("revsymb_id");
definition_id_names["revtypes"]           = QLatin1String("revtype_id");
definition_id_names["auctions"]           = QLatin1String("auction_id");
definition_id_names["catalogs"]           = QLatin1String("catalog_id");

worksheets << QLatin1String("denominations")
           << QLatin1String("states")
           << QLatin1String("epochs")
           << QLatin1String("notes")
           << QLatin1String("materials")
           << QLatin1String("edgeids")
           << QLatin1String("mints")
           << QLatin1String("types")
           << QLatin1String("undertypes")
           << QLatin1String("obvsymbs")
           << QLatin1String("obvtypes")
           << QLatin1String("revsymbs")
           << QLatin1String("revtypes")
           << QLatin1String("auctions")
           << QLatin1String("catalogs");

set_models( collNomTableView,
            QLatin1String("noms_reg"),
            tr("Denomination") );
set_models( collStatesTableView,
            QLatin1String("states_reg"),
            tr("State") );
set_models( collEpochsTableView,
            QLatin1String("epochs_reg"),
            tr("Epoch") );
set_models( collMarksTableView,
            QLatin1String("marks_reg"),
            tr("Notes") );
set_models( collMetalsTableView,
            QLatin1String("materials_reg"),
            tr("Material") );
set_models( collEdgeIDsTableView,
            QLatin1String("edgeids_reg"),
            tr("Edge ID") );
set_models( collMintTableView,
            QLatin1String("mints_reg"),
            tr("Mint") );
set_models( collTypesTableView,
            QLatin1String("types_reg"),
            tr("Type") );
set_models( collUndertypesTableView,
            QLatin1String("undertypes_reg"),
            tr("Undertype") );
set_models( collStatusTableView,
            QLatin1String("status_reg"),
            tr("Status") );
set_models( collUnitsTableView,
            QLatin1String("units_reg"),
            tr("Unit") );
set_models( collCurrTableView,
            QLatin1String("currency_reg"),
            tr("Currency") );
set_models( collCondTableView,
            QLatin1String("conditions_reg"),
            tr("Condition") );
set_models( collCertAuthTableView,
            QLatin1String("cert_auths_reg"),
            tr("Experts") );
set_models( collLocTableView,
            QLatin1String("location_reg"),
            tr("Location") );
set_models( collCatalogsTableView,
            QLatin1String("catalogs_reg"),
            tr("Catalog") );
set_models( collObvSymbolsTableView,
            QLatin1String("obvsymbs_reg"),
            tr("Obv. Symbol") );
set_models( collRevSymbolsTableView,
            QLatin1String("revsymbs_reg"),
            tr("Rev. Symbol") );
set_models( collObvTypesTableView,
            QLatin1String("obvtypes_reg"),
            tr("Obv. Type") );
set_models( collRevTypesTableView,
            QLatin1String("revtypes_reg"),
            tr("Rev. Type") );
set_models( collAuctTableView,
            QLatin1String("auctions_reg"),
            tr("Auction") );
set_models( collRecTypesTableView,
            QLatin1String("rectypes_reg"),
            tr("Record Type") );

QObject::connect( actionNoms,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_nom() ) );
QObject::connect( actionState,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_state() ) );
QObject::connect( actionEpoch,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_epoch() ) );
QObject::connect( actionMark,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_mark() ) );
QObject::connect( actionMetal,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_material() ) );
QObject::connect( actionEdgeID,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_edge() ) );
QObject::connect( actionMint,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_ms() ) );
QObject::connect( actionType,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_type() ) );
QObject::connect( actionUndertype,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_undertype() ) );
QObject::connect( actionNomsD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_nom() ) );
QObject::connect( actionStateD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_state() ) );
QObject::connect( actionEpochD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_epoch() ) );
QObject::connect( actionMarkD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_mark() ) );
QObject::connect( actionMetalD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT(delete_material()));
QObject::connect( actionEdgeIDD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_edge() ) );
QObject::connect( actionMintD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_ms() ) );
QObject::connect( actionTypeD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_type() ) );           
QObject::connect( actionUndertypeD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_undertype() ) );                  
QObject::connect( actionStatus,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_status() ) );
QObject::connect( actionUnits,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_unit() ) );
QObject::connect( actionCurr,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_curr() ) );
QObject::connect( actionCond,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_cond() ) );
QObject::connect( actionCA,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_cert() ) );
QObject::connect( actionLoc,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_loc() ) );
QObject::connect( actionCatalogs,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_catalog() ) );
QObject::connect( actionObvSymb,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_obvsymb() ) );
QObject::connect( actionRevSymb,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_revsymb() ) );
QObject::connect( actionObvType,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_obvtype() ) );
QObject::connect( actionRevType,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_revtype() ) );
QObject::connect( actionAuct,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_auct() ) );                  
QObject::connect( actionRecType,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( new_rectype() ) );                  
QObject::connect( actionStatusD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_status() ) );
QObject::connect( actionUnitsD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_unit() ) );
QObject::connect( actionCurrD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_curr() ) );
QObject::connect( actionCondD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_cond() ) );
QObject::connect( actionCAD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_cert() ) );
QObject::connect( actionLocD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_loc() ) );
QObject::connect( actionCatalogsD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_catalog() ) );
QObject::connect( actionObvSymbD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_obvsymb() ) );
QObject::connect( actionRevSymbD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_revsymb() ) );
QObject::connect( actionObvTypeD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_obvtype() ) );
QObject::connect( actionRevTypeD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_revtype() ) );
QObject::connect( actionAuctD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_auct() ) );
QObject::connect( actionRecTypeD,
                  SIGNAL( triggered() ),
                  this,
                  SLOT( delete_rectype() ) );                   
QObject::connect( closeToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( close() ) );
QObject::connect( importToolButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( import_xml_defs() ) );

}

CollAttr::~CollAttr()
{
}

void CollAttr::set_models( QTableView * tView,
                            QString table_string,
                            QString header )
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    }

QSqlTableModel * model = new QSqlTableModel(0, db);
model->setEditStrategy(QSqlTableModel::OnFieldChange);
QString model_table = QLatin1String("");
model_table.append(table_string);
model->setTable(model_table);
model->setSort(0, Qt::DescendingOrder);
model->select();
model->setHeaderData(1, Qt::Horizontal, header);
tView->setModel(model);
tView->setColumnWidth(1,360);
tView->hideColumn(0);
}

void CollAttr::delete_model(QTableView * tView)
{
QSqlTableModel * model = qobject_cast<QSqlTableModel *>( tView->model() );
    if (NULL != model)
    {
    model->clear();
    }
tView->setModel( new QSqlTableModel() );
delete model;
model = NULL;
}

void CollAttr::delete_models()
{
    for ( int y = 0; y < tableviews.size(); y++ )
    {
    delete_model( tableviews.at(y) );
    }
}

void CollAttr::new_row( QTableView * tView,
                        QString table_string,
                        QString id_field,
                        QString column_name )
{
QSqlTableModel * model = qobject_cast<QSqlTableModel *>( tView->model() );
    if (NULL == model)
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           QLatin1String("Model is null.") );
    return;
    }

model->setEditStrategy(QSqlTableModel::OnManualSubmit);

QSqlRecord record = construct_record( table_string, id_field, column_name );

bool success = model->insertRecord( -1, record );
    if (true != success)
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("The database reported : %1").arg( model->lastError().text() ) );
    model->revertAll();
    }

bool submit = model->submitAll();
    if (true != submit)
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("The database reported : %1").arg( model->lastError().text() ) );
    model->revertAll();
    }

model->setEditStrategy(QSqlTableModel::OnFieldChange);
model->setSort(0, Qt::DescendingOrder);
bool selected = model->select();
    if (true != selected)
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Can not select.") );
    }
}

QSqlRecord CollAttr::construct_record( QString table_string,
                                       QString id_field,
                                       QString column_name )
{
QSqlRecord record = QSqlRecord();
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    return record;
    }

QString s = QLatin1String("");
s.append( QLatin1String("select gen_id(") );
s.append(table_string);
s.append( QLatin1String("_gen") );
s.append( QLatin1String(", 1) from rdb$database") );

qint64 id;
id = Q_INT64_C(-1);
QSqlQuery query(s, db);
    while (query.next())
    {
    id = query.value(0).toLongLong();
    }
query.clear();
record.insert( 0, QSqlField(id_field, QVariant::LongLong) );
record.insert( 1, QSqlField(column_name, QVariant::String) );
record.setValue(id_field, id);
return record;
}

void CollAttr::new_nom()
{
new_row( collNomTableView,
         QLatin1String("noms_reg"),
         QLatin1String("nom_id"),
         QLatin1String("nom") );
}


void CollAttr::new_state()
{
new_row( collStatesTableView,
         QLatin1String("states_reg"),
         QLatin1String("state_id"),
         QLatin1String("state") );
}

void CollAttr::new_epoch()
{
new_row( collEpochsTableView,
         QLatin1String("epochs_reg"),
         QLatin1String("epoch_id"),
         QLatin1String("epoch") );
}

void CollAttr::new_mark()
{
new_row( collMarksTableView,
         QLatin1String("marks_reg"),
         QLatin1String("marks_id"),
         QLatin1String("mark") );
}


void CollAttr::new_edge()
{
new_row( collEdgeIDsTableView,
         QLatin1String("edgeids_reg"),
         QLatin1String("edgeid_id"),
         QLatin1String("edgeid") );
}

void CollAttr::new_material()
{
new_row( collMetalsTableView,
         QLatin1String("materials_reg"),
         QLatin1String("material_id"),
         QLatin1String("material") );
}

void CollAttr::new_ms()
{
new_row( collMintTableView,
         QLatin1String("mints_reg"),
         QLatin1String("mint_id"),
         QLatin1String("mint") );
}

void CollAttr::new_type()
{
new_row( collTypesTableView,
         QLatin1String("types_reg"),
         QLatin1String("type_id"),
         QLatin1String("obj_type") );
}

void CollAttr::new_undertype()
{
new_row( collUndertypesTableView,
         QLatin1String("undertypes_reg"),
         QLatin1String("undertype_id"),
         QLatin1String("undertype") );
}

void CollAttr::new_status()
{
new_row( collStatusTableView,
         QLatin1String("status_reg"),
         QLatin1String("status_id"),
         QLatin1String("status") );
}

void CollAttr::new_unit()
{
new_row( collUnitsTableView,
         QLatin1String("units_reg"),
         QLatin1String("unit_id"),
         QLatin1String("unit") );
}

void CollAttr::new_curr()
{
new_row( collCurrTableView,
         QLatin1String("currency_reg"),
         QLatin1String("currency_id"),
         QLatin1String("currency") );
}

void CollAttr::new_cond()
{
new_row( collCondTableView,
         QLatin1String("conditions_reg"),
         QLatin1String("condition_id"),
         QLatin1String("condition") );
}

void CollAttr::new_cert()
{
new_row( collCertAuthTableView,
         QLatin1String("cert_auths_reg"),
         QLatin1String("cert_auth_id"),
         QLatin1String("cert_auth") );
}

void CollAttr::new_loc()
{
new_row( collLocTableView,
         QLatin1String("locations_reg"),
         QLatin1String("location_id"),
         QLatin1String("location_name") );
}

void CollAttr::new_catalog()
{
new_row( collCatalogsTableView,
         QLatin1String("catalogs_reg"),
         QLatin1String("catalog_id"),
         QLatin1String("catalog_name") );
}

void CollAttr::new_obvsymb()
{
new_row( collObvSymbolsTableView,
         QLatin1String("obvsymbs_reg"),
         QLatin1String("obvsymb_id"),
         QLatin1String("obvsymb") );
}

void CollAttr::new_revsymb()
{
new_row( collRevSymbolsTableView,
         QLatin1String("revsymbs_reg"),
         QLatin1String("revsymb_id"),
         QLatin1String("revsymb") );
}

void CollAttr::new_obvtype()
{
new_row( collObvTypesTableView,
         QLatin1String("obvtypes_reg"),
         QLatin1String("obvtype_id"),
         QLatin1String("obvtype") );
}

void CollAttr::new_revtype()
{
new_row( collRevTypesTableView,
         QLatin1String("revtypes_reg"),
         QLatin1String("revtype_id"),
         QLatin1String("revtype") );
}

void CollAttr::new_auct()
{
new_row( collAuctTableView,
         QLatin1String("auctions_reg"),
         QLatin1String("auction_id"),
         QLatin1String("auction") );
}

void CollAttr::new_rectype()
{
new_row( collRecTypesTableView,
         QLatin1String("rectypes_reg"),
         QLatin1String("rectype_id"),
         QLatin1String("rectype") );
}

void CollAttr::delete_rows(QTableView * tView)
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( !db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    return;
    }


QSqlTableModel * model = qobject_cast<QSqlTableModel *>( tView->model() );
    if (NULL == model)
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          QLatin1String("Model is null.") );
    return;
    }

QItemSelectionModel * selectionModel = tView->selectionModel();
    if (NULL == selectionModel)
    {
    return;
    }
QModelIndexList currentSelection = selectionModel->selectedIndexes();

    if (currentSelection.isEmpty())
    {
    QMessageBox::information( this,
                              tr("Info"),
                              tr("Index is empty.") );
    return;
    }

QMessageBox mBox;
mBox.setWindowTitle( tr("Confirm") );
mBox.setText( tr("Delete?") );
mBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No );
    switch ( mBox.exec() )
    {
    case QMessageBox::No:
    return;
    break;

    default:
    break;
    }

model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    for (int i = 0; i < currentSelection.size(); ++i)
    {
        if (currentSelection.at(i).column() == 1)
        {
        bool success = model->removeRow( currentSelection.at(i).row() );
            if (true == success)
            {
            }
            else
            {
            QMessageBox::critical( this,
                                   tr("Model update failed"),
                                   tr("The database reported : %1").arg( model->lastError().text() ) );
            }
        }
    }

bool model_submit = model->submitAll();
    if (!model_submit)
    {
    QMessageBox::critical( this,
                           tr("Model submit failed"),
                           tr("The database reported : %1").arg( model->lastError().text() ) );
    }
    
model->setEditStrategy(QSqlTableModel::OnFieldChange);
model->select();
}

void CollAttr::delete_nom()
{
delete_rows(collNomTableView);
}

void CollAttr::delete_state()
{
delete_rows(collStatesTableView);
}

void CollAttr::delete_epoch()
{
delete_rows(collEpochsTableView);
}

void CollAttr::delete_mark()
{
delete_rows(collMarksTableView);
}


void CollAttr::delete_edge()
{
delete_rows(collEdgeIDsTableView);
}

void CollAttr::delete_material()
{
delete_rows(collMetalsTableView);
}

void CollAttr::delete_ms()
{
delete_rows(collMintTableView);
}

void CollAttr::delete_type()
{
delete_rows(collTypesTableView);
}

void CollAttr::delete_undertype()
{
delete_rows(collUndertypesTableView);
}

void CollAttr::delete_status()
{
delete_rows(collStatusTableView);
}

void CollAttr::delete_unit()
{
delete_rows(collUnitsTableView);
}

void CollAttr::delete_curr()
{
delete_rows(collCurrTableView);
}

void CollAttr::delete_cond()
{
delete_rows(collCondTableView);
}

void CollAttr::delete_cert()
{
delete_rows(collCertAuthTableView);
}

void CollAttr::delete_loc()
{
delete_rows(collLocTableView);
}

void CollAttr::delete_catalog()
{
delete_rows(collCatalogsTableView);
}

void CollAttr::delete_obvsymb()
{
delete_rows(collObvSymbolsTableView);
}

void CollAttr::delete_revsymb()
{
delete_rows(collRevSymbolsTableView);
}

void CollAttr::delete_obvtype()
{
delete_rows(collObvTypesTableView);
}

void CollAttr::delete_revtype()
{
delete_rows(collRevTypesTableView);
}

void CollAttr::delete_auct()
{
delete_rows(collAuctTableView);
}

void CollAttr::delete_rectype()
{
delete_rows(collRecTypesTableView);
}

void CollAttr::closeEvent(QCloseEvent * e)
{
delete_models();
emit reload_attrs();
writeSettings();
e->accept();
}

void CollAttr::writeSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);
settings.beginGroup( QLatin1String("CollAttr") );
settings.setValue( QLatin1String("size"), QVariant( this->size() ) );
settings.setValue( QLatin1String("pos"), QVariant( this->pos() ) );
settings.endGroup();
}

void CollAttr::readSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);                
settings.beginGroup( QLatin1String("CollAttr") );
resize( settings.value( QLatin1String("size"), QSize( 539, 300 ) ).toSize() );
move( settings.value( QLatin1String("pos"), QPoint( 0, 0 ) ).toPoint() );
settings.endGroup();
}

void CollAttr::import_xml_defs()
{
QSqlDatabase db = QSqlDatabase::database("collection", false);
    if ( true != db.isOpen() )
    {
    QMessageBox::warning( this,
                          tr("Error"),
                          tr("Database is closed.") );
    return;
    }

QString path = QLatin1String("");
ImportDefsDialog * dialog = new ImportDefsDialog;
dialog->show();
    if (dialog->exec() != QDialog::Accepted)
    {
    return;
    }
    else
    {
    path = dialog->return_selection();
    dialog->close();
    delete dialog;
    dialog = NULL;
    }

    if ( true == path.isEmpty() )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("File not selected.") );
    return;
    }

QFile file(path);
    if ( true != file.open( QFile::ReadOnly | QFile::Text ) )
    {
    QMessageBox::critical( this,
                           tr("Error"),
                           tr("Can not open file.") );
    return;
    }

QXmlInputSource * xmlInputSource = new QXmlInputSource(&file);

XMLParseDefs handler;
QXmlSimpleReader reader;
reader.setContentHandler(&handler);
reader.setErrorHandler(&handler);
QList< QMap<QString,QStringList> > d;
    if ( true == reader.parse(xmlInputSource, false ) )
    {
    d = handler.return_data();
    }
    else
    {
    QString error = handler.errorString();
    QMessageBox::critical( this,
                           tr("Error"),
                           error  );
    delete xmlInputSource;
    xmlInputSource = NULL;
    return;
    }

delete xmlInputSource;
xmlInputSource = NULL;
int count_sheets = 0;

    for (int z = 0; z < d.size(); z++)
    {
    QMap<QString,QStringList> mm = d.at(z);
    QMapIterator<QString,QStringList> mm_it(mm);
        while ( true == mm_it.hasNext() )
        {
        mm_it.next();
            if (worksheets.contains( mm_it.key(), Qt::CaseInsensitive ) )
            {
            count_sheets += 1;
            QStringList tl = mm_it.value();
                for (int u = 0; u < tl.size(); u++)
                {
                qint64 id = Q_INT64_C(-1);
                QString query_id_str = QLatin1String("select gen_id(");
                query_id_str.append( definition_tables.value( mm_it.key() ) );
                query_id_str.append(QLatin1String("_gen,1) from rdb$database"));
                QSqlQuery query_id(query_id_str, db);
                    while ( query_id.next() )
                    {
                    id = query_id.value(0).toLongLong();
                    }
                query_id.clear();
                
                QString query_str = QLatin1String("insert into ");
                query_str.append( definition_tables.value( mm_it.key() ) );
                query_str.append( QLatin1String("(") );
                query_str.append( definition_id_names.value( mm_it.key() ) );
                query_str.append( QLatin1String(",") );
                query_str.append( definition_field_names.value( mm_it.key() ) );
                query_str.append( QLatin1String(") values(") );
                query_str.append( QString::number(id) );
                query_str.append( QLatin1String(",") );
                query_str.append( QLatin1String("\'") );
                query_str.append( tl.at(u) );
                query_str.append( QLatin1String("\'") );
                query_str.append( QLatin1String(")") );
                QSqlQuery query_insert(query_str, db);
                    if ( true == query_insert.lastError().isValid() )
                    {
                    QMessageBox::warning( this,
                                          tr("Database Message"),
                                          query_insert.lastError().text() );
                    }
                query_insert.clear();
                }
            }
        }
    }

    for ( int y = 0; y < tableviews.size(); y++ )
    {
    QTableView * tV = tableviews.at(y);
    QSqlTableModel * model = qobject_cast<QSqlTableModel *>( tV->model() );
        if (NULL != model)
        {
        model->select();
        }
    }

qApp->processEvents();
file.close();

    if ( count_sheets > 0 )
    {
    QMessageBox::information( this,
                              tr("Information"),
                              tr("Definition imported.") );
    }
    else
    {
    QMessageBox::warning( this,
                          tr("Warning"),
                          tr("Required worksheets were not found.\nNothing imported.") );
    }

}
